package com.have.blog.base.exception;

import com.have.blog.base.constant.BaseConstant;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import java.util.List;
import java.util.Objects;

/**
 * 抛出异常工具类
 */
public class ThrowableUtils {

    /**
     * 校验参数正确，瓶装字段名和值的错误信息
     * @param result
     */
    public static void checkParamArgument(BindingResult result) {
        if (result != null && result.hasErrors()) {
            StringBuilder sb = new StringBuilder();
            List<FieldError> errors = result.getFieldErrors();
            if (!CollectionUtils.isEmpty(errors)) {
                FieldError fieldError = errors.get(0);
                String rejectValue = Objects.toString(fieldError.getRejectedValue(), "");
                String defMsg = fieldError.getDefaultMessage();
                if (rejectValue.contains(BaseConstant.DELIMITER_TO)) {
                    sb.append(defMsg);
                } else {
                    sb.append(fieldError.getField()).append(" ").append(defMsg);
                }
            } else {
                String msg = result.getAllErrors().get(0).getDefaultMessage();
                sb.append(msg);
            }
            throw new ApiInvalidParamException(sb.toString());
        }
    }
}
